import axios from 'axios'
import helper from './helper.js'
import qs from 'qs'

import Vue from 'vue';
import {Toast} from 'vant';
Vue.use(Toast);

if(process.env.NODE_ENV=='production'){
    axios.defaults.baseURL = process.env.API_HOST;
}else{
    axios.defaults.baseURL = '/'
    // axios.defaults.baseURL =' http://whou.xufengyingshi.com/api.php/';
    // axios.defaults.baseURL ='http://api.caixuyingshi.com/api';
    // axios.defaults.baseURL ='http://api.caixuyingshi.com/';
}

// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// axios.defaults.withCredentials=true; //让ajax携带cookie

function apiAxios(method, url, params, token='111') {
console.log(url,method,params);
  return new Promise((resolve,reject) => {
    axios({
      method: method,
      //拼接参数
      url: method === 'GET'|| method === 'DELETE' ? helper.queryString(url,params) : url,
      data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null,
      timeout: 10000,
		header: {
		  'Access-Control-Allow-Origin': '*',
		},
       headers: {

				 'content-type': 'application/x-www-form-urlencoded',
				 // 'Authorization': `Bearer ${token}`
				 },
      withCredentials: true
    })
    .then(response => {
      // console.log(response)
      if(response.data.code == 1||response.data.code == 200){
        // console.log(response.data)
        resolve(response.data);
      }else{
        //Toast.fail(response.data.msg);
        Toast({
          message: response.data.msg,
          icon: 'cross',
        });
      }
    })
    .catch(err => {
      reject(err)
    })
  })
}

export default {
  get: function (url, params, token) {
    return apiAxios('GET', url, params, token)
  },
  post: function (url, params, token) {
    return apiAxios('POST', url, params, token)
  },
  put: function (url, params, token) {
    return apiAxios('PUT', url, params, token)
  },
  delete: function (url, params, token) {
    return apiAxios('DELETE', url, params, token)
  },
}
